<!--
 * @Description: 
 * @Author: chenju
 * @Date: 2022-03-17 10:53:23
 * @LastEditors: chenju
 * @LastEditTime: 2022-12-07 16:42:02
-->
<template>
  <CPageLayout :headerConfig="headerConfig">
    <template #headerDesc>
      <div class="g-flex-start-center">
        <span>组织名称：{{ empty(taskInfo?.organizationName) }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>创建人：{{ empty(taskInfo?.creator) }}({{ empty(taskInfo?.creatorEmail) }})</span>
        <el-divider direction="vertical"></el-divider>
        <span>创建时间：{{ empty(taskInfo?.createTime) }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>补充说明：{{ empty(taskInfo?.additionRemark) }}</span>
      </div>
    </template>
    <CPageTable @register="registerPage">
      <template #headerRightButton>
        <el-button
          type="primary"
          @click="handleAutoAccounting"
          v-btnPermission="'ECI_INVENTORY_TASK_ACCOUNT'"
          >{{
            taskInfo?.accountStandards && taskInfo?.accountStandards.length > 0
              ? '重新核算'
              : '自动核算'
          }}</el-button
        >
      </template>
      <vxe-column title="组织名称/任务编号" min-width="130" tree-node>
        <template #default="scope">
          <CTableColumn :main-text="scope.row.organizationName" :sub-text="scope.row.taskNo" />
        </template>
      </vxe-column>
      <vxe-column title="数据状态" width="200">
        <template #default="scope">
          <template v-if="scope.row.boundaryType === BoundaryTypeEnum.SELF_FILL">
            <div class="g-flex-start-center" v-if="!scope.row.totalNum">
              <CIcon class="data-status-icon" type="c-mian-jinggao"></CIcon>
              <span class="g-font-12n3-2">未匹配到活动数据</span>
            </div>
            <CLink @click="handleOpenActiveDataDialog(scope.row)"
              >已完成 {{ scope.row.matchNum }} 期，累计 {{ scope.row.totalNum }} 期
            </CLink>
          </template>
          <span v-else>-</span>
        </template>
      </vxe-column>
      <vxe-column title="核算标准" min-width="200">
        <template #default="scope">
          <template v-if="scope.row.boundaryType === BoundaryTypeEnum.SELF_FILL">
            <div v-for="item in scope.row.accountStandards" :key="item.gwpVersion">
              <CLink @click="standardClick(item.standard, item.gwpVersion)">
                {{
                  CarbonInventoryStandardsMap[
                    item.standard as keyof typeof CarbonInventoryStandardsMap
                  ]
                }}{{ item.gwpVersion ? `(${item.gwpVersion})` : '' }}
              </CLink>
            </div>
          </template>
          <span v-else>-</span>
        </template>
      </vxe-column>
      <vxe-column title="创建时间" width="170">
        <template #default="scope">
          <span>{{ empty(scope.row.createTime) }}</span>
        </template>
      </vxe-column>
      <vxe-column title="核算时间" width="170">
        <template #default="scope">
          <template v-if="scope.row.boundaryType === BoundaryTypeEnum.SELF_FILL">
            <span>{{ empty(scope.row.accountTime) }}</span>
          </template>
          <span v-else>-</span>
        </template>
      </vxe-column>
      <vxe-column title="核算状态" width="90" fixed="right">
        <template #default="scope">
          <el-tag
            class="g-tag"
            hit
            :type="getTaskStatusTagType(scope.row.accountStatus)"
            v-if="scope.row.boundaryType === BoundaryTypeEnum.SELF_FILL"
            >{{ scope.row.accountStatus ? $t18(`eci.${scope.row.accountStatus}`) : '-' }}</el-tag
          >
          <span v-else>-</span>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="90" fixed="right">
        <template #default="scope">
          <CTableButtonGroup
            :buttons-config="getTableButtonsConfig(scope.row)"
            v-if="
              scope.row.boundaryType === BoundaryTypeEnum.SELF_FILL &&
              scope.row.accountStatus === AccountStatusEnum.ACCOUNTED
            "
          ></CTableButtonGroup>
        </template>
      </vxe-column>
    </CPageTable>
    <ActiveDataDialog
      v-model:visible="activeVisible"
      :taskNo="activeTaskNo"
      :title="activeDialogTitle"
    ></ActiveDataDialog>
    <AutoAccountingDialog
      v-model:visible="autoAccountingVisible"
      :taskNo="taskNo"
      @refresh="handleRefresh"
    ></AutoAccountingDialog>
  </CPageLayout>
</template>
<script lang="ts">
export default {
  name: 'InventoryTaskDetail'
};
</script>
<script lang="ts" setup>
import { Ref, ref, reactive, nextTick, computed } from 'vue';
import ActiveDataDialog from './components/ActiveDataDialog/index.vue';
import AutoAccountingDialog from './components/AutoAccountingDialog/index.vue';
import { CTableButtonGroup, CTableColumn } from '@/components/CTable/index';
import type { TableButtonItem } from '@/components/CTable';
import { empty } from '@/utils';
import { getTaskInfo, getTaskTree } from '@/apis/eci/emissionAccounting/inventoryTask';
import type {
  GetTaskInfoResult,
  TaskDetailChildTaskItem
} from '@/apis/eci/emissionAccounting/model/inventoryTaskModel';
import { useRoute } from 'vue-router';
import { AccountStatusEnum } from '@/constants/enum';
import { handleStandardsFormat } from '@/utils/eci';
import { VxeTablePropTypes } from '@xfchenju/vxe-table';
import { CPageLayout, CPageHeaderComplexProps } from '@/components/CPageLayout';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { useRouter } from 'vue-router';
import { CLink } from '@/components/CLink/index';
import { CarbonInventoryStandardsMap, BoundaryTypeEnum } from '@/constants/enum';

interface TaskDetailTableRowType extends TaskDetailChildTaskItem {
  level: number;
}
const route = useRoute();
const router = useRouter();
const taskNo = route.params.taskNo as string;
function getTaskStatusTagType(accountStatus: keyof typeof AccountStatusEnum) {
  switch (accountStatus) {
    case AccountStatusEnum.ACCOUNTED:
      return 'success';
    case AccountStatusEnum.NOT_ACCOUNT:
      return 'info';
    default:
      return 'info';
  }
}

function handleRefresh() {
  console.log('handleRefresh');
  refresh();
}

const tableConfig = reactive({
  treeConfig: {
    expandAll: true,
    rowField: 'taskNo',
    children: 'childTaskList',
    iconOpen: 'c-mian-xia iconfont',
    iconClose: 'c-mian-you iconfont'
  } as VxeTablePropTypes.TreeConfig
});

const extraTableOption = {
  treeConfig: tableConfig.treeConfig,
  scrollY: { enabled: true },
  maxHeight: '800px',
  rowConfig: { height: 68 }
};

async function loadData() {
  try {
    taskInfoLoading.value = true;
    taskInfo.value = await getTaskInfo(taskNo);
    taskInfoLoading.value = false;
    return getTaskTree(taskNo).then(res => {
      console.log('getTaskTree', res);
      setTimeout(() => {
        handleExpandAll();
      }, 0);
      return {
        records: res || [],
        total: res?.length || 0
      };
    });
  } catch (error) {
    console.log('error', error);
    taskInfoLoading.value = false;
    return false;
  }
}

const taskInfoLoading = ref(false);
const taskInfo = ref<GetTaskInfoResult>();

/**
 * 自动核算弹窗状态
 */
const autoAccountingVisible = ref(false);

/**
 * 自动核算按钮
 */
function handleAutoAccounting() {
  console.log('handleAutoAccounting');
  autoAccountingVisible.value = true;
}
const standardClick = (standard: string, gwpVersion: string) => {
  localStorage.setItem('inventoryTaskId', taskNo);
  //
  router.push(
    `/reportFormManagement/report?standard=${standard}&gwpVersion=${gwpVersion}&inventoryYear=${taskInfo.value?.inventoryYear}&orgCode=${taskInfo.value?.organizationCode}&orgName=${taskInfo.value?.organizationName}`
  );
};

/**
 * 活动数据相关
 */
const activeVisible = ref(false);
const activeDialogTitle = ref('');
const activeTaskNo = ref('');
function handleOpenActiveDataDialog(row: TaskDetailTableRowType) {
  activeDialogTitle.value = `${row.organizationName}-${taskInfo.value?.inventoryYear}-活动数据`;
  activeTaskNo.value = row.taskNo;
  activeVisible.value = true;
}

/**
 * 展开所有节点
 */
function handleExpandAll() {
  operationTable((baseTableRef: Ref<any>) => {
    console.log('getTaskTree', baseTableRef.value.setAllTreeExpand);
    baseTableRef.value?.setAllTreeExpand(true);
  });
}

const headerConfig = computed<CPageHeaderComplexProps>(() => {
  return {
    title: `${empty(taskInfo.value?.inventoryYear)} _ ${empty(
      taskInfo.value?.organizationName
    )} _ 盘查任务`
  };
});

function handleViewDetail(row: TaskDetailTableRowType) {
  router.push(
    `/carbonManagement/carbonList/carbonDetail?taskNo=${row.taskNo}&title=${row.organizationName}`
  );
}

/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(row: TaskDetailTableRowType): TableButtonItem[] {
  return [
    {
      text: '清册',
      btnPermission: 'ECI_INVENTORY_DETAIL_VIEW',
      onClick: () => handleViewDetail(row)
    }
  ];
}

const options = reactive<CPageTableProps>({
  title: '组织边界',
  descText: '请设定核算标准后，进行自动核算。',
  isDetailPage: true,
  isShowSearchBar: false,
  tableOptions: {
    loadData,
    rowKey: 'taskNo',
    extraTableOption: extraTableOption,
    pagination: false
  }
});
const [registerPage, { refresh, operationTable }] = useCPageTable(options);
</script>
<style lang="scss" scoped>
.block {
  display: block;
}
:deep(.c-page-table) {
  .c-page-table__body .c-page-table__body-main.c-page-table__body-main--hide-search-bar {
    padding-top: 16px;
    padding-bottom: 60px;
  }
}
.data-status-icon {
  margin-right: 4px;
  font-size: 14px;
  color: #e1b205;
}

.task-detail-container {
  padding: 0 32px 32px;
  :deep(.el-table__header-wrapper) {
    padding: 0;
  }
  .task-detail-page-header {
    z-index: 1;
    position: relative;
    background: #fff;
    border-radius: 4px 4px 0 0;
    box-shadow: 0px 8px 8px 2px #f6f9fa;
  }
  .task-detail-subtitle-text {
    font-size: 14px;
    font-family: SourceHanSansCN-Regular, SourceHanSansCN;
    font-weight: 400;
    color: #489375;
    line-height: 22px;
  }
  .task-detail-detail-popover-container {
    padding: 20px 24px;
  }
  .task-detail-list-container {
    margin-top: 20px;
    background: #fff;
    width: 100%;
    height: 400px;
    border-radius: 4px;
    .list-container-header {
      height: 56px;
      padding: 0 24px;
      border-bottom: 1px solid #ebeef5;
    }
    .list-container-body {
      padding-bottom: 24px;
      .subtask-parent-icon {
        font-size: 16px;
        color: #51596c;
      }
    }
  }
}

// 表格第一行 将原本tree的部分隐藏
:deep(.el-table) {
  .el-table__body-wrapper {
    tr td:first-child {
      .el-table__expand-icon {
        display: none !important;
      }
      .el-table__placeholder {
        display: none !important;
      }
    }
  }
}

// 新的tree的icon样式
.g-table__expand-icon {
  font-size: 12px;
  line-height: 23px;
  color: #ced4da;
  cursor: pointer;
  :deep(.icon) {
    transition: transform 0.3s;
  }
  &.g-table__expand-icon--hide {
    opacity: 0;
    cursor: default;
    // margin-right: 0;
    // > :deep(.icon) {
    //   width: 0;
    // }
  }
  &.g-table__expand-icon--expanded {
    :deep(.icon) {
      transform: rotate(90deg);
    }
  }
}
:deep(.c-base-table) {
  .vxe-tree--btn-wrapper {
    top: 10px;
    .vxe-tree--node-btn {
      color: #435970 !important;
    }
  }
}
</style>
